package org.broadway.scripting;

import groovy.util.ScriptException;

/***
 * The BsfScriptRunner class provide functionalities that wrap
 * and encapsulates the logic necessary to execute scripting files
 * using BSF.
 * @see ScriptRunner
 * @see ScriptEngine
 * @see BsfScriptEngine
 * @author vladimir vivien
 *
 */
public class BsfScriptRunner implements ScriptRunner<Object> {

	private BsfScriptEngine engine;
	private String fileName;
	
	private void validate() {
		if(this.getScriptEngine() == null)
			throw new ScriptingException("Unable to run script because ScriptEngine not set properly.");
	}
	
	public BsfScriptRunner(){}
	
	/**
	 * Constructor that accepts a ScriptEngine.
	 * @param engine
	 */
	public BsfScriptRunner(ScriptEngine engine) {
		this.setScriptEngine(engine);
	}
	
	/**
	 * Constructor that accepts and script engine and file name to run.
	 * @param engine - ScriptEngine.
	 * @param fileName - scripting file path.
	 */
	public BsfScriptRunner(ScriptEngine engine, String fileName) {
		this.setScriptEngine(engine);
		this.setScriptLocation(fileName);
	}
	
	/**
	 * Use this method to add variables and their values that will
	 * be exposed to the execution of the script file at runtime.
	 */
	public void putParameter(String param, Object value) {
		this.getScriptEngine().putVariable(param, value);
		
	}

	/**
	 * Getter that returns a ScriptEngine.
	 * @return
	 */
	public ScriptEngine getScriptEngine() {
		if(engine == null)
			engine = new BsfScriptEngine();
		return engine;
	}

	/**
	 * Setter that sets ScriptEngine.
	 */
	public void setScriptEngine(ScriptEngine engine) {
		this.engine = (BsfScriptEngine) engine;
	}

	/**
	 * Set script file location
	 */
	public void setScriptLocation(String fileName) {
		this.fileName = fileName;
	}
	
	/**
	 * Getter that returns the script location.
	 * @return
	 */
	public String getScriptLocation() {
		return this.fileName;
	}
	
	/**
	 * The implementation method for the ScriptRunner.
	 * Call this method to run and execut the script file set on this
	 * component.
	 * @return Object any value returned by the execution of the script file.
	 * @throws ScriptException thrown if anything goes wrong.
	 */
	public Object run() throws ScriptingException{
		validate();
		return this.getScriptEngine().exec(this.getScriptLocation());
		
	}
}
